﻿using CFree.Common.Script;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using XLua;

public class LuaManager : BaseManager
{
    LuaEnv luaEnv;

    private void Awake()
    {
        InitEnv();
    }

    private void Start()
    {
       
    }

    void Update()
    {
        if (luaEnv != null)
        {
            luaEnv.Tick();
        }
    }

    void OnDestroy()
    {
        if (luaEnv != null) { 
            luaEnv.Dispose();
        }
    }

// ===================================== unity生命周期函数与功能函数分割线
    public void InitEnv()
    {
        Assert.IsNull(luaEnv);

        luaEnv = new LuaEnv();

#if UNITY_STANDALONE_WIN
        luaEnv.AddLoader(StreamingLuaLoader.Load);
#endif
        luaEnv.AddLoader(RawLuaLoader.Load);
        //luaEnv.DoString("package.path=package.path..';" + LuaConst.LuaDir + "?.lua" + "'");
        //eg:设置require搜索路径时的加载器,这里返回空还会继续搜索其他默认lua文件搜索路径
        //luaEnv.AddLoader((ref string filename) =>
        //{
        //    if (filename == "InMemory")
        //    {
        //        string script = "return {ccc = 9999}";
        //        return System.Text.Encoding.UTF8.GetBytes(script);
        //    }
        //    return null;
        //});

        //string luaCmd = string.Format("require '{0}'", LuaConst.LuaEntranceScript);
        //DoString(luaCmd);
        //BindGameTickFunc();
    }

    void CallLuaGlobalFunction(string funcName)
    {
        var func = luaEnv.Global.Get<Action>(funcName);
        if (func is null)
        {
            Debug.LogError("Cannot find global lua function:" + funcName);
            return;
        }
        func();
    }

    /// <summary>
    /// c#调用lua 或者 lua调用c#
    /// </summary>
    /// <param name="luaScript">代码</param>
    public void DoString(string script)
    {
        Assert.IsNotNull(script, "DoString:script对象为空");
        Assert.IsNotNull(luaEnv, "DoString: luaEnv 为空");
        luaEnv.DoString(script);
    }

    public LuaTable GetGlobal()
    {
        return luaEnv.Global;
    }

    public void StartLua()
    {
        string startLuaScript = @"
            local luaInit = require ('LuaInit')
            luaInit.StartGame()
            --print(package.path)
            --print(package.cpath)

        ";
        DoString(startLuaScript);
    }
}
